package com.travel.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.commons.utils.R;
import com.travel.modules.sys.dao.SysUserTokenDao;
import com.travel.modules.sys.entity.SysUserToken;
import com.travel.modules.sys.oauth2.TokenGenerator;
import com.travel.modules.sys.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service("SysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserToken> implements SysUserTokenService {
    @Resource
    private SysUserTokenDao sysUserTokenDao;

    /* 一天有多少秒 */
    private static final int DAY_SECOND = 24 * 3600;

    @Override
    public R generateToken(Integer userId, int valid) {
        /* 随机生成token */
        String token = TokenGenerator.generateValue();

        Date now = new Date();
        /* 生成过期时间 */
        Date expire = new Date(now.getTime() + (long) valid * DAY_SECOND * 1000);// 2个月

        SysUserToken userToken = sysUserTokenDao.selectById(userId);
        if (userToken == null) {
            userToken = new SysUserToken();
            userToken.setUserId(userId);
            userToken.setToken(token);
            userToken.setExpireTime(expire);

            sysUserTokenDao.save(userToken);
        } else {
            userToken.setToken(token);
            userToken.setExpireTime(expire);
            userToken.setUpdateTime(now);

            sysUserTokenDao.updateById(userToken);
        }
        return R.ok().put("token", token).put("expire",DAY_SECOND);
    }

    @Override
    public void logout(Integer userId) {
        String token = TokenGenerator.generateValue();

        SysUserToken userToken = new SysUserToken();
        userToken.setUserId(userId);
        userToken.setToken(token);
        userToken.setUpdateTime(new Date());
        sysUserTokenDao.updateById(userToken);
    }
}
